#include "Stroke.h"
#include "icanvas.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>

static void EnlargeRect(RECT* pRect, long n);
static bool CheckIntersect(RECT* pRect1, RECT* pRect2);

CStroke::CStroke ()
{
   m_bText = false;
   m_text.ptext = NULL;
   m_pNext = NULL;
}

CStroke::~CStroke()
{
   if (m_bText && m_text.ptext) {
      free (m_text.ptext);
   }
}

char* CStroke::CopyString (char* str)
{
   if (m_bText && m_text.ptext) {
      free (m_text.ptext);
   }
   m_bText = true;
   m_text.ptext = (char*) malloc (strlen(str) +1);
   strcpy (m_text.ptext, str);
   return m_text.ptext;
}

bool CStroke::Intersect(ICanvas* pCanvas, RECT& rc)
{
   if (!m_bText) {
      return IntersectLine(rc);
   }
   assert (pCanvas);
   return IntersectText(pCanvas, rc);
}

bool CStroke::IntersectLine(RECT& rc)
{
   assert (!m_bText);
   RECT rcLine;

   rcLine.left = (m_line.from.x <= m_line.to.x ? m_line.from.x : m_line.to.x);
   rcLine.right = (m_line.from.x >= m_line.to.x ? m_line.from.x : m_line.to.x);
   rcLine.top = (m_line.from.y <= m_line.to.y ? m_line.from.y : m_line.to.y);
   rcLine.bottom = (m_line.from.y >= m_line.to.y ? m_line.from.y : m_line.to.y);
   EnlargeRect (&rcLine, m_line.penwidth/2+1);

   return CheckIntersect (&rc, &rcLine);
}

bool CStroke::IntersectText(ICanvas* pCanvas, RECT& rc)
{
   assert (m_bText);
   assert (m_text.ptext);
   assert (pCanvas);
   RECT rcText;

   if (pCanvas->GetTextRect(m_text, rcText) != 0) {
      return false;
   }
   return CheckIntersect (&rc, &rcText);
}


// helpers
static void EnlargeRect(RECT* pRect, long n)
{
   assert (pRect);
   pRect->left -= n;
   pRect->right += n;
   pRect->top -= n;
   pRect->bottom += n;
}

static bool CheckIntersect(RECT* pRect1, RECT* pRect2)
{
   assert (pRect1 && pRect2);
   assert (pRect1->left <= pRect1->right);
   assert (pRect1->top <= pRect1->bottom);
   assert (pRect2->left <= pRect2->right);
   assert (pRect2->top <= pRect2->bottom);

   if (((pRect1->right < pRect2->left) || (pRect2->right < pRect1->left)) ||
       ((pRect1->bottom < pRect2->top) || (pRect2->bottom < pRect1->top))) {
      return false;
   }
   return true; 
}
